package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 初始化加载lua脚本
     */
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    /**
     * 异步处理任务线程池
     */
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    /**
     * 在类初始化之后执行，因为当这个类初始化好了之后，随时都是有可能要执行的
     */
    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    // 阻塞队列
//    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);

    IVoucherOrderService proxy = null;

    private class VoucherOrderHandler implements Runnable {
        private static final String STREAM_KEY = "stream.orders";
        // 通过redis Stream消息队列获取订单信息
        @Override
        public void run() {
            while (true) {
                try {
                    // 0. 检查 Stream key 是否存在
                    Long size = stringRedisTemplate.opsForStream().size(STREAM_KEY);
                    if (size <=0){
                        // 队列不存在，直接结束循环。并打印日志信息
                        log.error("key为{}的消息队列不存在，请检查配置", STREAM_KEY);
                        break;
                    }
                    // 1.从redis Stream消息队列获取订单信息  XGROUPREAD GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> orders = stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(STREAM_KEY, ReadOffset.lastConsumed())
                    );
                    // 2.判断订单信息是否为空
                    if (orders == null || ObjectUtil.isEmpty(orders)) {
                        // 继续循环
                        continue;
                    }
                    // 3.创建订单
                    MapRecord<String, Object, Object> record = orders.get(0);
                    Map<Object, Object> orderInfo = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(orderInfo, new VoucherOrder(), true);
                    createVoucherOrder(voucherOrder);
                    // 4.确认消息 ACK XACK key group consumer_name ID [ID ...]
                    stringRedisTemplate.opsForStream().acknowledge(STREAM_KEY, "g1", record.getId());
                } catch (Exception e) {
                    // 处理异常
                    log.error("处理订单异常", e);
                    // 处理异常消息
                    handleExceptionRecord();
                }

            }
        }


        /**
         * 处理异常消息
         */
        private void handleExceptionRecord() {
            while (true) {
                try {
                    // 1.从redis pending-list消息队列获取订单信息  XGROUPREAD GROUP g1 c1 COUNT 1 STREAMS stream.orders 0
                    List<MapRecord<String, Object, Object>> orders = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create("stream.orders", ReadOffset.from("0"))
                    );
                    // 2.判断订单信息是否为空
                    if (orders == null || ObjectUtil.isEmpty(orders)) {
                        // 说明消息队列中已没有异常消息，直接结束循环
                        break;
                    }
                    // 3.创建订单
                    MapRecord<String, Object, Object> record = orders.get(0);
                    Map<Object, Object> orderInfo = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(orderInfo, new VoucherOrder(), true);
                    createVoucherOrder(voucherOrder);
                    // 4.确认消息 ACK XACK key group consumer_name ID [ID ...]
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());
                } catch (Exception e) {
                    // 打印错误日志，继续处理下一条消息
                    log.error("处理订单异常", e);
                }
            }
        }


        // 废弃 通过阻塞队列获取订单
        /*@Override
        public void run() {
            try {
                // 1.从任务队列中获取订单信息
                VoucherOrder voucherOrder = orderTasks.take();
                // 2.创建订单
                handleVoucherOrder(voucherOrder);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }*/

        private void handleVoucherOrder(VoucherOrder voucherOrder) {
            //1.获取用户
            Long userId = voucherOrder.getUserId();
            // 2.创建锁对象
            RLock redisLock = redissonClient.getLock("lock:order:" + userId);
            // 3.尝试获取锁
            boolean isLock = redisLock.tryLock();
            // 4.判断是否获得锁成功
            if (!isLock) {
                // 获取锁失败，直接返回失败或者重试
                log.error("不允许重复下单！");
                return;
            }
            try {
                //注意：由于是spring的事务是放在threadLocal中，此时的是多线程，事务会失效
                proxy.createVoucherOrder(voucherOrder);
            } finally {
                // 释放锁
                redisLock.unlock();
            }
        }
    }

    /**
     * 根据阻塞队列订单信息，创建订单
     *
     * @param voucherOrder
     */
    @Override
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        // 保证一人一单
        Integer count = query().eq("voucher_id", voucherId)
                .eq("user_id", userId).count();
        if (count > 0) {
            log.info("id为：" + userId + "的用户已经购买过该秒杀券");
        }

        // 扣减库存，添加乐观锁
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                // 这种方式反而会增加下单的失败率
//                .eq("stock", voucher.getStock())
                // 只要我库存还大于0，就允许用户继续下单
                .gt("stock", 0)
                .update();
        if (!success) {
            log.info("秒杀券已售罄");
        }
        // 生成订单
        save(voucherOrder);
        log.info("订单生成成功，订单id：{}", voucherOrder.getId());
    }

    /**
     * 优化优惠卷订单秒杀：
     * 1、主线程仅判断当前用户是否具备资格下单
     * 2、开启子线程完成创建订单操作
     *
     * @param voucherId 秒杀券id
     * @return 订单id
     */
    @Override
    public Result order(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        Long orderId = redisIdWorker.nextId("order");
        // 执行lua脚本
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT, Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                orderId.toString());
        int r = result.intValue();
        // 2.判断结果是否为0
        if (r != 0) {
            // 2.1.不为0 ，代表没有购买资格
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        return Result.ok(orderId);
    }

    /*@Override
    public Result order(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        Long orderId = redisIdWorker.nextId("order");
        // 执行lua脚本
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT, Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                orderId.toString());
        int r = result.intValue();
        // 2.判断结果是否为0
        if (r != 0) {
            // 2.1.不为0 ，代表没有购买资格
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        // 将订单信息添加到阻塞队列中
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setId(orderId);
        orderTasks.add(voucherOrder);
        //3.获取代理对象，将代理对象传递下去，避免事务失效
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(orderId);
    }*/

    /**
     * 下单购买秒杀券
     * 使用乐观锁解决超卖题
     *
     * @param voucherId 秒杀券id
     * @return 订单id
     */
    /*@Override
    public Result order(Long voucherId) {
        // 查询优惠券信息
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        if (ObjectUtil.isEmpty(voucher)) {
            return Result.fail("id为" + voucherId + "的秒杀券不存在");
        }
        // 判断秒杀是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀还未开始");
        }
        // 判断秒杀是否结束
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀已结束");
        }
        // 判断秒杀券是否已售罄
        if (voucher.getStock() < 1) {
            return Result.fail("秒杀券已售罄");
        }

        // 保证一人一单
        Long userId = UserHolder.getUser().getId();

//        // 3、事务提交后，锁会被释放
//        synchronized (userId.toString().intern()) {
//            // 获取代理对象，代理对象才具备事务功能
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.oneUserAndOrder(voucherId);
//        }

        // 方法一：使用自定义分布式锁
//        SimpleRedisLock lock = new SimpleRedisLock(stringRedisTemplate, "order:" + userId);

        // 方法二：使用Redission分布式锁
        RLock lock = redissonClient
                .getLock("lock:order:" + userId);
        // 尝试获取锁
        boolean isLock = lock.tryLock();
        if (!isLock) {
            return Result.fail("不允许重复下单");
        }
        try {
            return oneUserAndOrder(voucherId);
        } finally {
            lock.unlock();
        }
    }*/

    /**
     * 一人一单
     *
     * @param voucherId
     * @return
     */
    @Transactional
    /*
        1、将锁放在方法体上，那么这个方法就是一个同步方法，只有一个线程能够进入，会导致性能问题
     */
    public /*synchronized */Result oneUserAndOrder(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        /*
            2、将锁放在方法体内存在的问题：方法执行完毕后，锁会被释放，但事务是由Spring管理的
            此时，事务还未提交，锁就被释放了，下一个进程进来，仍会出现线程安全问题
         */
//        synchronized (userId.toString().intern()){
        // 保证一人一单
        Integer count = query().eq("voucher_id", voucherId)
                .eq("user_id", userId).count();
        if (count > 0) {
            return Result.fail("id为：" + userId + "的用户已经购买过该秒杀券");
        }

        // 扣减库存，添加乐观锁
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                // 这种方式反而会增加下单的失败率
//                .eq("stock", voucher.getStock())
                // 只要我库存还大于0，就允许用户继续下单
                .gt("stock", 0)
                .update();
        if (!success) {
            return Result.fail("秒杀券已售罄");
        }
        // 生成订单
        VoucherOrder order = new VoucherOrder();
        long orderID = redisIdWorker.nextId("order");
        order.setId(orderID);
        order.setVoucherId(voucherId);
        order.setUserId(UserHolder.getUser().getId());
        save(order);
        return Result.ok(orderID);
    }
//    }
}
